package com.dsl.dslsuzhou.service;

import com.dsl.dslsuzhou.model.dto.DeviceImportDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备导入服务
 */
@Service
public class DeviceImportService {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    /**
     * 批量导入设备数据
     */
    @Transactional
    public Map<String, Object> importDevices(List<DeviceImportDto> devices) {
        Map<String, Object> result = new HashMap<>();
        List<String> errors = new ArrayList<>();
        int successCount = 0;
        int errorCount = 0;
        
        try {
            for (int i = 0; i < devices.size(); i++) {
                DeviceImportDto device = devices.get(i);
                try {
                    // 验证必填字段
                    if (!validateDevice(device, i + 1, errors)) {
                        errorCount++;
                        continue;
                    }
                    
                    // 处理设备分组
                    if (StringUtils.hasText(device.getDeviceGroupId()) && StringUtils.hasText(device.getDeviceGroupName())) {
                        ensureMachineGroupExists(device.getDeviceGroupId(), device.getDeviceGroupName());
                    }

                    // 插入或更新设备
                    insertOrUpdateDevice(device);

                    // 创建设备与分组的关联
                    if (StringUtils.hasText(device.getDeviceGroupId())) {
                        createDeviceGroupRelation(device.getDeviceId(), device.getDeviceGroupId());
                    }
                    
                    successCount++;
                    
                } catch (Exception e) {
                    errorCount++;
                    errors.add("第" + (i + 1) + "行数据处理失败: " + e.getMessage());
                }
            }
            
            result.put("code", errors.isEmpty() ? 200 : 206);
            result.put("message", String.format("导入完成，成功: %d条，失败: %d条", successCount, errorCount));
            result.put("successCount", successCount);
            result.put("errorCount", errorCount);
            result.put("errors", errors);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "批量导入失败: " + e.getMessage());
            List<String> errorList = new ArrayList<>();
            errorList.add(e.getMessage());
            result.put("errors", errorList);
        }
        
        return result;
    }
    
    /**
     * 验证设备数据
     */
    private boolean validateDevice(DeviceImportDto device, int rowNum, List<String> errors) {
        boolean isValid = true;

        if (!StringUtils.hasText(device.getDeviceId())) {
            errors.add("第" + rowNum + "行: 设备ID不能为空");
            isValid = false;
        }

        if (!StringUtils.hasText(device.getDeviceName())) {
            errors.add("第" + rowNum + "行: 设备名称不能为空");
            isValid = false;
        }

        return isValid;
    }
    
    /**
     * 确保机组存在
     */
    private void ensureMachineGroupExists(String groupId, String groupName) {
        String checkSql = "SELECT COUNT(*) FROM dim_machine_group WHERE machine_group_id = ?";
        Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, groupId);

        if (count == 0) {
            String insertSql = "INSERT INTO dim_machine_group (machine_group_id, group_name) VALUES (?, ?)";
            jdbcTemplate.update(insertSql, groupId, groupName);
        }
    }

    /**
     * 插入或更新设备
     */
    private void insertOrUpdateDevice(DeviceImportDto device) {
        String checkSql = "SELECT COUNT(*) FROM dim_device WHERE device_id = ?";
        Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, device.getDeviceId());

        if (count > 0) {
            // 更新设备
            String updateSql = "UPDATE dim_device SET device_name = ?, device_model = ?, " +
                             "device_type = ?, device_category = ?, device_secret = ?, updated_at = NOW() " +
                             "WHERE device_id = ?";
            jdbcTemplate.update(updateSql,
                device.getDeviceName(),
                device.getDeviceModel(),
                device.getDeviceTypeKey(),
                device.getDeviceTypeName(),
                device.getDeviceSecret(),
                device.getDeviceId());
        } else {
            // 插入设备
            String insertSql = "INSERT INTO dim_device (device_id, device_name, device_model, " +
                             "device_type, device_category, device_secret) VALUES (?, ?, ?, ?, ?, ?)";
            jdbcTemplate.update(insertSql,
                device.getDeviceId(),
                device.getDeviceName(),
                device.getDeviceModel(),
                device.getDeviceTypeKey(),
                device.getDeviceTypeName(),
                device.getDeviceSecret());
        }
    }

    /**
     * 创建设备与分组的关联关系
     */
    private void createDeviceGroupRelation(String deviceId, String groupId) {
        // 检查关联是否已存在
        String checkSql = "SELECT COUNT(*) FROM bridge_device_machine_group " +
                         "WHERE device_id = ? AND machine_group_id = ? AND (end_date IS NULL OR end_date > CURDATE())";
        Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, deviceId, groupId);

        if (count == 0) {
            // 创建新的关联关系
            String insertSql = "INSERT INTO bridge_device_machine_group " +
                             "(device_id, machine_group_id, relationship_type, start_date) " +
                             "VALUES (?, ?, 'primary', CURDATE())";
            jdbcTemplate.update(insertSql, deviceId, groupId);
        }
    }
}
